package com.hckjsec.oa.controller;

import java.util.*;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.util.StringUtil;
import com.hckjsec.common.utils.DateUtils;
import com.hckjsec.common.utils.SecurityUtils;
import com.hckjsec.common.utils.StringUtils;
import com.hckjsec.framework.aspectj.DataScopeAspect;
import com.hckjsec.oa.domain.*;
import com.hckjsec.oa.domain.OaView.HomeSignView;
import com.hckjsec.oa.flow.FlowPath;
import com.hckjsec.oa.service.*;
import com.hckjsec.system.domain.SysPost;
import com.hckjsec.system.service.ISysPostService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.hckjsec.common.annotation.Log;
import com.hckjsec.common.core.controller.BaseController;
import com.hckjsec.common.core.domain.AjaxResult;
import com.hckjsec.common.enums.BusinessType;
import com.hckjsec.common.utils.poi.ExcelUtil;
import com.hckjsec.common.core.page.TableDataInfo;

/**
 * 公司OA申请Controller
 * 
 * @author cyt
 * @date 2021-12-31
 */
@RestController
@RequestMapping("/oa/apply")
public class OaApplyController extends BaseController
{
    @Autowired
    private IOaApplyService oaApplyService;
    @Autowired
    private IOaDateService oaDateService;
    @Autowired
    private IOaAttendanceService oaAttendanceService;
    @Autowired
    private IOaConfigService oaConfigService;
    @Autowired
    private IOaAuditingService oaAuditingService;
    @Autowired
    private ISysPostService postService;

    /**
     * 查询公司OA申请列表
     */
    @GetMapping("/list")
    public TableDataInfo list(OaApply oaApply)
    {
        startPage();
        oaApply.getParams().put("authority", DataScopeAspect.getDataScopeSql(SecurityUtils.getSysUser()));
        List<OaApply> list = oaApplyService.selectOaApplyList(oaApply);
        list.forEach(kv->{
            kv.setDurationStr(DateUtils.getIntervalStr(kv.getDuration()));
        });
        return getDataTable(list);
    }

    /**
     * 导出公司OA申请列表
     */
    @Log(title = "公司OA申请", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(OaApply oaApply)
    {
        List<OaApply> list = oaApplyService.selectOaApplyList(oaApply);
        ExcelUtil<OaApply> util = new ExcelUtil<OaApply>(OaApply.class);
        return util.exportExcel(list, "apply");
    }

    /**
     * 获取公司OA申请详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(oaApplyService.selectOaApplyById(id));
    }

    /**
     * 新增公司OA申请
     */
    @Log(title = "公司OA申请", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody OaApply oaApply)
    {
        oaApply.setState("0");
        oaApply.setCreateBy(SecurityUtils.getUsername());
        return toAjax(oaApplyService.insertOaApply(oaApply));
    }

    /**
     * 修改公司OA申请
     */
    @Log(title = "公司OA申请", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OaApply oaApply)
    {
        oaApply.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(oaApplyService.updateOaApply(oaApply));
    }

    /**
     * 删除公司OA申请
     */
    @Log(title = "公司OA申请", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        //判断只能删除自己申请的或状态是待审核的
        boolean flag = true;
        Long  userId = SecurityUtils.getUserId();
        for (int i = 0; i < ids.length ; i++) {
            OaApply oaApply = oaApplyService.selectOaApplyById(ids[i]);
            if (!userId.equals(oaApply.getUserId()) || !"0".equals(oaApply.getState())){
                flag = false;
                break;
            }
        }
        if (!flag){
            return AjaxResult.error("存在不能删除的记录!");
        }
        return toAjax(oaApplyService.deleteOaApplyByIds(ids));
    }



    /**
     * 获取加班时间列表
     */
    @PostMapping(value = "/getMyOvertime")
    public AjaxResult getMyOvertime()
    {
        List<OaApply>  applyList = new ArrayList<>();
        Long  userId = SecurityUtils.getUserId();
        //获取配置
        OaConfig oaConfig = new OaConfig();
        List<OaConfig> configList = oaConfigService.selectOaConfigList(null);
        if (!StringUtils.isEmpty(configList)){
            oaConfig = configList.get(0);
        }
        //获取上月到昨天加班列表
//        String   startTime =  DateUtils.getPastMonth(1)+"-01";//获取上个月第一天
        String   startTime =  DateUtils.getPastDate(10);//获取前10天日期
        String   endTim = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,DateUtils.getNowDate());
        OaDate oaDate = new  OaDate();
        oaDate.setBeginTime(startTime);
        oaDate.setEndTime(endTim);
        List<OaDate> oaDateList = oaDateService.selectOaDateList(oaDate);
        LinkedHashMap<Date, Long> calendarMap = new LinkedHashMap<>();
        oaDateList.forEach(kv->{
            calendarMap.put(kv.getDate(),kv.getFestival());
        });
        OaAttendance findOaAttendance = new  OaAttendance();
        findOaAttendance.setBeginTime(startTime);
        findOaAttendance.setEndTime(endTim);
        findOaAttendance.setUserId(userId);
        findOaAttendance.setPeriod("1");
        findOaAttendance.getParams().put("overtime", "overtime");
        List<OaAttendance> oaAttendanceList =  oaAttendanceService.selectOaAttendanceList(findOaAttendance);
        OaConfig finalOaConfig = oaConfig;
        oaAttendanceList.forEach(kv->{
            OaApply   oaApply  = new   OaApply();
            //如果是假日加班   起始时间从签到时间算起
            String oldDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,kv.getDate())+" "+ finalOaConfig.getEndWorkTime()+":00";
            Long festival = calendarMap.get(kv.getDate());
            if (festival == 1){
                OaAttendance oaAttendance = new  OaAttendance();
                oaAttendance.setDate(kv.getDate());
                oaAttendance.setUserId(userId);
                oaAttendance.setPeriod("0");
                List<OaAttendance> oaAttendanceList1 =  oaAttendanceService.selectOaAttendanceList(oaAttendance);
                if (StringUtils.isNotEmpty(oaAttendanceList1)){
                    oldDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,oaAttendanceList1.get(0).getPthTime());

                }
            }
            Date oldDate = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS,oldDateStr);//应该签退时间
            Date findDate = kv.getPthTime();//打卡时间
            long interval = (findDate.getTime() - oldDate.getTime())/1000;
            if (interval > 1800){//加班时间超过半小时 算加班
                oaApply.setDate(kv.getDate());
                oaApply.setDeptId(kv.getDeptId());
                oaApply.setUserId(kv.getUserId());
                oaApply.setUserName(kv.getUserName());
                oaApply.setApplyType("overtime");
                oaApply.setStartDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,oldDate));
                oaApply.setEndDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,findDate));
                oaApply.setDuration(interval);
                oaApply.setDurationStr(DateUtils.getIntervalStr(interval));
                applyList.add(oaApply);
            }
        });
        return AjaxResult.success(applyList);
    }


    /**
     * 获取公司OA申请审核详细信息
     */
    @GetMapping(value = "/auditing/{id}")
    public AjaxResult getAuditingInfo(@PathVariable("id") Long id)
    {
        OaApply oaApply = oaApplyService.selectOaApplyById(id);
        oaApply.setDurationStr(DateUtils.getIntervalStr(oaApply.getDuration()));
        OaAuditing oaAuditing = new OaAuditing();
        oaAuditing.setType("overtime");
        oaAuditing.setOutsideId(oaApply.getId());
        List<OaAuditing> auditingList = oaAuditingService.selectOaAuditingList(oaAuditing);
        oaApply.setAuditingList(auditingList);
        boolean isAuditor = false;
        if (!"0".equals(oaApply.getState())){
            isAuditor = false;
        }else {
            //判断当前用户是否允许可以审批
            List<String> codeList = new ArrayList<>();
            Long userId = SecurityUtils.getUserId();
            List<Integer> postList = postService.selectPostListByUserId(userId);
            List<SysPost> postAllList = postService.selectPostList(null);
            postAllList.forEach(kv -> {
                if (postList.contains(kv.getPostId().intValue())) {
                    codeList.add(kv.getPostCode());
                }
            });
            if (!StringUtils.isEmpty(auditingList)) {
                isAuditor = FlowPath.isAuditing(codeList, "overtime", auditingList.get(auditingList.size() - 1).getSchedule());
            } else {
                isAuditor = FlowPath.isAuditing(codeList, "overtime", "");
            }
        }
        oaApply.setAuditor(isAuditor);
        //仅测试  上线删除
        if(SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            oaApply.setAuditor(true);
        }
        return AjaxResult.success(oaApply);
    }

    /**
     * 加班审核接口
     */
    @PostMapping(value = "/setAuditor")
    public AjaxResult setAuditor(@RequestBody OaAuditing oaAuditing)
    {
        OaAuditing oldOaAuditing = new OaAuditing();
        oldOaAuditing.setType("overtime");
        oldOaAuditing.setOutsideId(oaAuditing.getOutsideId());
        List<OaAuditing> auditingList = oaAuditingService.selectOaAuditingList(oldOaAuditing);
        int index = 0;
        if (!StringUtils.isEmpty(auditingList)){
            index = Arrays.binarySearch(FlowPath.OA_OVERTIME, auditingList.get(auditingList.size() - 1).getSchedule()) + 1;
        }
        oaAuditing.setSchedule(FlowPath.OA_OVERTIME[index]);
        oaAuditing.setType("overtime");
        oaAuditing.setAuditorTime(DateUtils.getNowDate());
        oaAuditing.setAuditorId(SecurityUtils.getUserId());
        oaAuditing.setAuditorName(SecurityUtils.getNickName());
        int rows = oaAuditingService.insertOaAuditing(oaAuditing);
        if (rows > 0){
            OaApply oaApply = oaApplyService.selectOaApplyById(oaAuditing.getOutsideId());
             if ("1".equals(oaAuditing.getState())){
                 oaApply.setState("2");
                 oaApplyService.updateOaApply(oaApply);
             }else{
                 if ((FlowPath.OA_OVERTIME.length - 1) == index) {//最后一个流程
                     oaApply.setState("1");
                     oaApplyService.updateOaApply(oaApply);
                 }
             }
        }
        return toAjax(rows);
    }
}
